<template>
  <div class="app-container">
    <div class="page-header">
      <el-button @click="goBack" icon="el-icon-back">返回订单列表</el-button>
      <div class="actions">
        <el-button
          v-if="orderData.status === '0'"
          type="success"
          @click="handleShip"
          >发货</el-button
        >
        <el-button
          v-if="orderData.status === '0'"
          type="danger"
          @click="handleCancel"
          >取消订单</el-button
        >
      </div>
    </div>

    <el-card v-if="loading" class="loading-card">
      <div class="loading-container">
        <el-skeleton style="width: 100%" animated>
          <template #template>
            <el-skeleton-item
              variant="text"
              style="width: 100%; height: 40px; margin-bottom: 20px"
            />
            <el-skeleton-item variant="text" style="width: 60%; height: 20px" />
            <el-skeleton-item
              variant="text"
              style="width: 50%; height: 20px; margin: 10px 0"
            />
            <el-skeleton-item
              variant="text"
              style="width: 70%; height: 20px; margin-bottom: 20px"
            />
            <el-skeleton-item variant="p" style="width: 100%; height: 300px" />
          </template>
        </el-skeleton>
      </div>
    </el-card>

    <el-empty
      v-else-if="error || !orderData.order_id"
      :description="error || '订单不存在或已被删除'"
    ></el-empty>

    <div v-else class="order-detail">
      <div class="order-header">
        <h1>
          订单详情 <span class="order-id">#{{ orderData.order_id }}</span>
        </h1>
        <div class="order-meta">
          <div
            class="status-badge"
            :class="{
              'status-pending': orderData.status === '0',
              'status-completed': orderData.status === '1',
              'status-canceled': orderData.status === '2',
            }"
          >
            {{ getStatusText(orderData.status) }}
          </div>
          <div class="order-date">
            下单时间: {{ formatDate(orderData.orderDate) }}
          </div>
        </div>
      </div>

      <div class="info-section">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-card">
              <h3>收货信息</h3>
              <div class="info-item">
                <strong>收货人:</strong> {{ orderData.recipient }}
              </div>
              <div class="info-item">
                <strong>联系电话:</strong> {{ orderData.phone }}
              </div>
              <div class="info-item">
                <strong>收货地址:</strong> {{ orderData.address }}
              </div>
            </div>
          </el-col>

          <el-col :span="12">
            <div class="info-card">
              <h3>订单信息</h3>
              <div class="info-item">
                <strong>订单编号:</strong> {{ orderData.order_id }}
              </div>
              <div class="info-item">
                <strong>下单时间:</strong> {{ formatDate(orderData.orderDate) }}
              </div>
              <div class="info-item">
                <strong>订单状态:</strong> {{ getStatusText(orderData.status) }}
              </div>
              <div class="info-item">
                <strong>支付方式:</strong>
                {{ orderData.paymentMethod || "在线支付" }}
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <div class="products-section">
        <h3>订单商品</h3>
        <el-table :data="orderData.books" border style="width: 100%">
          <el-table-column label="图书封面" width="120">
            <template #default="scope">
              <el-image
                style="width: 50px; height: 70px"
                :src="scope.row.img"
                :alt="scope.row.booksname"
                :preview-src-list="[scope.row.img]"
                fit="contain"
              />
            </template>
          </el-table-column>
          <el-table-column prop="bookname" label="图书名称">

      

          </el-table-column>
          <el-table-column prop="price" label="单价" >
            <template #default="scope"> ¥{{ scope.row.price }} </template>
          </el-table-column>
          <el-table-column
            prop="num"
            label="数量"
         
          ></el-table-column>
          <el-table-column label="小计" >
            <template #default="scope">
              ¥{{ (scope.row.price * scope.row.num).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="order-summary">
        <div class="summary-item">
          <span>商品总金额:</span>
          <span class="amount">¥{{ orderData.totalprice }}</span>
        </div>
        <div class="summary-item">
          <span>运费:</span>
          <span class="amount">¥0.00</span>
        </div>
        <div class="summary-item total">
          <span>订单总计:</span>
          <span class="amount">¥{{ orderData.totalprice }}</span>
        </div>
      </div>

      <div v-if="orderData.status === '1'" class="logistics-section">
        <h3>物流信息</h3>
        <div class="info-card">
          <div class="info-item">
            <strong>快递公司:</strong>
            {{ orderData.expressCompany || "顺丰速运" }}
          </div>
          <div class="info-item">
            <strong>快递单号:</strong>
            {{ orderData.trackingNumber || "SF1234567890" }}
          </div>
          <div class="info-item">
            <strong>发货时间:</strong>
            {{ formatDate(orderData.shippingTime) || "未知" }}
          </div>
        </div>
      </div>
    </div>

    <!-- 发货对话框 -->
    <el-dialog title="订单发货" v-model="dialogShipVisible" width="500px">
      <el-form
        ref="shipFormRef"
        :model="shipForm"
        :rules="shipRules"
        label-width="100px"
      >
        <el-form-item label="订单号" prop="orderId">
          <el-input v-model="shipForm.orderId" disabled />
        </el-form-item>
        <el-form-item label="快递公司" prop="expressCompany">
          <el-select
            v-model="shipForm.expressCompany"
            placeholder="请选择快递公司"
          >
            <el-option label="顺丰速运" value="顺丰速运" />
            <el-option label="中通快递" value="中通快递" />
            <el-option label="圆通速递" value="圆通速递" />
            <el-option label="韵达快递" value="韵达快递" />
            <el-option label="申通快递" value="申通快递" />
          </el-select>
        </el-form-item>
        <el-form-item label="快递单号" prop="trackingNumber">
          <el-input v-model="shipForm.trackingNumber" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogShipVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmShip">确认发货</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
// import axios from "../../utils/request";
import { orderAPI } from "../../utils/api";

const route = useRoute();
const router = useRouter();
const loading = ref(true);
const error = ref(null);
const orderData = ref({});
const dialogShipVisible = ref(false);
const shipFormRef = ref(null);

// 发货表单
const shipForm = reactive({
  orderId: "",
  expressCompany: "",
  trackingNumber: "",
});

// 发货表单验证规则
const shipRules = {
  expressCompany: [
    { required: true, message: "请选择快递公司", trigger: "change" },
  ],
  trackingNumber: [
    { required: true, message: "请输入快递单号", trigger: "blur" },
  ],
};

// 获取订单详情
const getOrderDetail = async () => {
  loading.value = true;
  error.value = null;

  try {
    const orderId = route.params.id;
    if (!orderId) {
      error.value = "订单ID不能为空";
      loading.value = false;
      return;
    }

    const res = await orderAPI.getDetail(orderId);
    if (res.code === 200) {
      orderData.value = res.data || {};
    } else {
      error.value = res.message || "获取订单详情失败";
      ElMessage.error(error.value);
    }
  } catch (err) {
    console.error("获取订单详情错误:", err);
    error.value = err.message || "获取订单详情失败";
    ElMessage.error(error.value);
  } finally {
    loading.value = false;
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case "0":
      return "待发货";
    case "1":
      return "已发货";
    case "2":
      return "已取消";
    default:
      return "未知状态";
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return "未知日期";
  const date = new Date(dateString);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
};

// 返回订单列表
const goBack = () => {
  router.push("/orders");
};

// 处理发货
const handleShip = () => {
  shipForm.orderId = orderData.value.order_id;
  shipForm.expressCompany = "";
  shipForm.trackingNumber = "";
  dialogShipVisible.value = true;
};

// 确认发货
const confirmShip = () => {
  shipFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await orderAPI.ship({
          orderId: shipForm.orderId,
          expressCompany: shipForm.expressCompany,
          trackingNumber: shipForm.trackingNumber,
        });

        if (res.code === 200) {
          // 更新订单状态
          orderData.value.status = "1";
          orderData.value.expressCompany = shipForm.expressCompany;
          orderData.value.trackingNumber = shipForm.trackingNumber;
          orderData.value.shippingTime = new Date().toLocaleString();
          ElMessage.success("发货成功");
          dialogShipVisible.value = false;
        } else {
          ElMessage.error(res.message || "发货失败");
        }
      } catch (error) {
        console.error("发货错误:", error);
        ElMessage.error("发货失败: " + (error.message || "未知错误"));
      }
    }
  });
};

// 取消订单
const handleCancel = () => {
  ElMessageBox.confirm("确定要取消此订单吗？此操作不可撤销。", "取消订单", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await orderAPI.cancel(orderData.value.order_id);
        if (res.code === 200) {
          orderData.value.status = "2";
          ElMessage.success("订单已取消");
        } else {
          ElMessage.error(res.message || "取消订单失败");
        }
      } catch (error) {
        console.error("取消订单错误:", error);
        ElMessage.error("取消订单失败: " + (error.message || "未知错误"));
      }
    })
    .catch(() => {
      // 用户取消操作
    });
};

// 页面加载时获取数据
onMounted(() => {
  getOrderDetail();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.actions {
  display: flex;
  gap: 10px;
}

.loading-card {
  padding: 20px;
  margin-bottom: 20px;
}

.loading-container {
  width: 100%;
}

.order-header {
  display: flex;
  flex-direction: column;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.order-header h1 {
  font-size: 24px;
  margin: 0 0 10px 0;
  color: #303133;
}

.order-id {
  color: #909399;
  font-weight: normal;
}

.order-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-badge {
  font-weight: bold;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
}

.status-pending {
  background-color: #ecf5ff;
  color: #409eff;
}

.status-completed {
  background-color: #f0f9eb;
  color: #67c23a;
}

.status-canceled {
  background-color: #fef0f0;
  color: #f56c6c;
}

.order-date {
  color: #909399;
  font-size: 14px;
}

.info-section {
  margin-bottom: 30px;
}

.info-card {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  height: 100%;
}

.info-card h3 {
  font-size: 16px;
  margin-top: 0;
  margin-bottom: 15px;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.info-item {
  margin-bottom: 10px;
  color: #606266;
}

.info-item strong {
  color: #303133;
  margin-right: 5px;
}

.products-section {
  margin-bottom: 30px;
}

.products-section h3 {
  font-size: 16px;
  margin-bottom: 15px;
  color: #303133;
}

.order-summary {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 30px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  color: #606266;
}

.summary-item.total {
  font-weight: bold;
  border-top: 1px solid #ebeef5;
  padding-top: 10px;
  margin-top: 10px;
  color: #303133;
}

.amount {
  min-width: 100px;
  text-align: right;
}

.total .amount {
  color: #f56c6c;
  font-size: 18px;
}

.logistics-section {
  margin-bottom: 30px;
}

.logistics-section h3 {
  font-size: 16px;
  margin-bottom: 15px;
  color: #303133;
}

@media (max-width: 768px) {
  .order-meta {
    flex-direction: column;
    align-items: flex-start;
  }

  .status-badge {
    margin-bottom: 10px;
  }

  .info-section .el-col {
    margin-bottom: 20px;
  }
}
</style>
